<?php

namespace App\Http\Controllers\Api;

use App\Dao\SettingDao;
use App\Exceptions\ApiErrorException;
use Illuminate\Support\Facades\Cache;
use GatewayWorker\Lib\Gateway AS GatewayLib;
use DB;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Dao\UploadedFileDao;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\Calculation\Category;
use App\Models\Topics;
use App\Models\Shares;
use App\Models\Users;
use App\Models\Orders;
use App\Models\Donates;
use Illuminate\Support\Facades\Cookie;

class HomeController extends Controller
{

    public function __construct()
    {
        parent::_init();
        
    }
    /**
     * 微信分享等sdk
     *  author yh
     * 
     */
    public function getConfig(Request $request)
    {
        //获取参数
        $url = $request->get('url');
        //公众号的appid、secret
        $appid = "wx2d3960047c6f754f";
        $secret = "35acfd6b84e18a1bed203cce17528c33";
        //缓存内是否存在accessToken。
        $accessToken = Cache::remember('accessToken11', 120, function () use ($appid, $secret) {
            //获取access_token的请求地址
            $accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            //请求地址获取access_token
            $accessTokenJson = file_get_contents($accessTokenUrl);
            $accessTokenObj = json_decode($accessTokenJson);
            $accessToken = $accessTokenObj->access_token;
            return $accessToken;
        });
 
        //获取jsapi_ticket的请求地址
        $ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi";
        $jsapiTicketJson = file_get_contents($ticketUrl);
        $jsapiTicketObj = json_decode($jsapiTicketJson);
        $jsapiTicket = $jsapiTicketObj->ticket;
        //随机生成16位字符
        $noncestr = str_random(16);
        //时间戳
        $time = time();
        //拼接string1
        $jsapiTicketNew = "jsapi_ticket=$jsapiTicket&noncestr=$noncestr&timestamp=$time&url=$url";
        //对string1作sha1加密
        $signature = sha1($jsapiTicketNew);
        //存入数据
        $data = [
            'appid' => $appid,
            'timestamp' => $time,
            'nonceStr' => $noncestr,
            'signature' => $signature,
            'jsapiTicket' => $jsapiTicket,
            'url' => $url,
            'jsApiList' => [
                'api' => '#'
            ]
        ];
        //返回
        return json_encode($data);
    }
    public function getTopicDetail(){
        $data = Topics::where('id',request('id'))->first();
        Topics::where('id', request('id'))->increment('times'); //自增次数
        if($data){
           $shares = Shares::where('id',$data['share_id'])->first();
           if($shares){
             $data['shareInfo']=$shares;
           }
           if(!$shares){ 
               $datas['title'] = '众筹分享';
               $datas['imgs'] = base_path('./img/logo.png');
               $data['shareInfo']= $datas;
           }
           if($data->joins>=$data->num){
            $data->status=3;
           }
            $api_token= request('api_token');
            $data->isjoin=0;
           if(!$api_token){
            if (!Auth::user()) {
                return response_json(405, '', '登录已过期，请重新登录');
               }
           }else{
            $uid = Auth::user()->uid;
            $user = Users::where('uid', $uid)->first();
            $order = Orders::where('openid',$user->openid)->where('topic_id',request('id'))->first();
            if(isset($order)){
                $data->isjoin = 1;
            }
            $data->openid = $user->openid;
           }
           $data->nowdate = strtotime(date('Y-m-d H:i:s'));
           $data->banners = explode(',',$data->banners);
           $data->start_date = strtotime($data->start_date);
           $data->end_date =strtotime($data->end_date);
           
           return response_json(1, $data,'success');  
        }
        return response_json(0, $data,'error');
    }
    /**
     * 微信用户授权登录
     */
    public function get_login(){
        $id= request('id');
        $shareId = request('shareId')|0;
        $appid = "wx2d3960047c6f754f";
        $secret = "35acfd6b84e18a1bed203cce17528c33";
        $redirect_uri = urlencode ("https://www.shenhaijiyuan.com/api/userLogin?p=w&id=$id&shareId=$shareId");
        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
        header("Location:".$url);
    }

    /**
     *  微信授权回调地址
     * 
     * */ 
    public function userLogin(){
        $code = request("code");
        $appid = "wx2d3960047c6f754f";
        $secret = "35acfd6b84e18a1bed203cce17528c33";
        function getJson($url){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
        }
        //第一步:取得openid
        $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $oauth2 = json_decode(getJson($oauth2Url));
        //print_r($oauth2); 
        $access_token = $oauth2->access_token; 
        print_r($access_token);

        $openid= $oauth2->openid; 
        $checkToken = "https://api.weixin.qq.com/sns/auth?access_token=$access_token&openid=$openid";
        $userinfo = getJson($checkToken);
        $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $userinfo = json_decode(getJson($get_user_info_url));
        $user= Users::where('openid',$openid)->first();
        // 判断是否用户存在
        if(!$user){
            $user = new Users();
            $user->nickname= $userinfo->nickname;
            $user->openid = $userinfo->openid;
            $user->username = '';
            $user->avatar = $userinfo->headimgurl;
            $user->phone = '';
            $user->lastloginip = client_real_ip();
            $user->plat = request('p');
            $user->shareId = request('shareId');
            $user->save();
            $user->api_token = get_api_token($user->uid);
            $user->save();
        }else{
            $user->avatar = $userinfo->headimgurl;
            $user->api_token = get_api_token($user->uid);
            $user->save();
        }
        $id= request('id');
        $api_token = $user->api_token;
        $url = "https://www.shenhaijiyuan.com/wap/#/?id=$id&api_token=$api_token";
        header("Location:".$url); 
    }
    /**
     * 获取众筹活动须知协议等
     * @author yh
     * @api getInfo
     */
    public function getInfo(){
        $topic = Topics::where('id',request('id'))->first();
        return response_json(1, $topic,'success');
    }
    /**
     *  参加众筹
     */
    public function join_topic(){
        $api_token = request('api_token');
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $user = Users::where('uid', $uid)->first();
        
        $topic = Topics::where('id',request('id'))->first();
        if($topic->joins>=$topic->num){
            return response_json(0,'','该活动人数已满，下次再来吧');
        }
        $times= strtotime($topic->start_date);
        $nowtime = strtotime(date('Y-m-d H:i:s'));
        if($nowtime<$times){
            return response_json(0,'','活动未开始，请稍后再来吧');
        }
        $endtime = strtotime($topic->end_date);
        if($nowtime>$endtime){
            return response_json(0,'', '活动已结束，请稍后再来吧');
        }
        $order= Orders::where('topic_id',request('id'))->where('openid',$user->openid)->first();
        if($order){
            return response_json(0,'','您已经参与过了，去看看别的活动吧！');
        }
        $order = new Orders();
        $order->title= $topic->title;
        $order->money = $topic->money;
        $order->topic_id = $topic->id;
        $order->openid = $user->openid;
        $order->nickname = $user->nickname;
        $order->num = 0;
        $order->total =0;
        $order->order_sn = 'SHJY' . date('ymdHi') . rand(1000, 9999);
        $order->save();
        $order->avatar = $user->avatar;
        $topic->joins= $topic->joins +1;
        $topic->save();
        return response_json(1, $order,'参加成功');
    }

    /**
     * 获取我的众筹情况
     * @api getList
     * @author yh
     * @method get
     */
    public function getList(){
        $api_token = request('api_token');
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $user = Users::where('uid', $uid)->first();
        $order = Orders::where('openid',$user->openid)->where('topic_id',request('id'))->first();
        $lists = Donates::where('openid',$user->openid)->where('status',4)->get();
        $data['list'] = $lists;
        $data['total'] = $order->total;
        $data['num'] = $order->num;
        $data['avatar'] =$user->avatar;
        $data['nickname']= $user->nickname;
        $data['money'] =$order->money;
        $data['status'] = $order->status;
        return  response_json(1, $data,'message');
    }
    /**
     * @api getOrder
     * @method post
     * @author yh 
     *
     */
    public function getOrder()
    {
        
        $orders = Orders::where('topic_id',request('id'))->where('status',request('type'))->get();
        foreach($orders as $item){
            $user = Users::where('openid',$item->openid)->first();
            $item['avatar']= $user->avatar;
            $sort = request('sort', 'created_at');
            $order = request('order', 'desc');
            $list = Donates::orderBy($sort, $order)->where('openid',$item->openid)->skip(0)->limit(5)->get();
            $item['list'] = $list;
        }
        return response_json(1,$orders,'success');
    }
    /**
     * @api getTotal
     * @author yh
     * 
     */
    public function getTotal(){
        $orders = Orders::where('topic_id',request('id'))->get();
        foreach($orders as $item){
            $user = Users::where('openid',$item->openid)->first();
            $item['avatar']= $user->avatar;
            $sort = request('sort', 'created_at');
            $order = request('order', 'desc');
            $list = Donates::orderBy($sort, $order)->where('openid',$item->openid)->skip(0)->limit(5)->get();
            $item['list'] = $list;
        }
        return response_json(1,$orders,'success');
    }
    
	/**
	 * 创建订单并支付
	 *
	 * @author yh 20201126
	 * @return \Illuminate\Http\JsonResponse
	 * @throws ApiErrorException
	 * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
	 *
	 * @api {POST} /ticketorder/pay 2. 订单支付(儿童乐园线下扫码共用)
	 * @apiGroup TicketOrder
	 * @apiVersion 1.0.0
	 * @apiParam {string} p 平台，w：Web，wx：微信
	 * @apiParam {string} [api_token] 用户签名
	 * @apiParam {int} torder_id 订单id
	 * @apiParam {int} payment_id 支付类型，1：微信，2：微信小程序，4：支付宝
	 * @apiSuccess {object} data 返回数据
	 * @apiSuccess {int} data.torder_id 订单id
	 * @apiSuccess {string} data.order_sn 订单号
	 * @apiSuccess {object} data.wxpayinfo 微信支付相关数据
	 * @apiSuccess {object} data.alipayinfo 支付宝支付相关数据
	 * @apiSuccess {object} data.bcmpayinfo 交通银行支付相关数据
	 * @apiSuccess {string} data.bcmpayinfo.BocomURL POST请求地址
	 * @apiSuccess {string} data.bcmpayinfo.RSASignData 支付数据
	 * @apiSuccess {string} data.bcmpayinfo.qrcode 支付二维码url
	 * @apiSuccessExample {json} 微信及小程序支付
	 * {"status":1,"msg":"","data":{"torder_id":2,"order_sn":"GHYM19041517268568","wxpayinfo":{"appId":"wxf9204fd29cb51160","timeStamp":"1555320657","nonceStr":"5cb44f515c12e","package":"prepay_id=wx151730573402064ef9b4c5701139496107","signType":"MD5","paySign":"CD191A81D24F7A4E5C1D3098B48AAD25"}}}
	 * @apiSuccessExample {json} H5支付
	 * {"status":1,"msg":"","data":{}}
	 * @apiSuccessExample {json} 微信扫码支付，PC用
	 * {"status":1,"msg":"","data":{"qrcode":"weixin:\/\/wxpay\/bizpayurl?appid=wxf9204fd29cb51160&mch_id=1530450181&time_stamp=1555310179&nonce_str=5cb42663e4c56&product_id=pw_1&sign=9880A66C3F18BFAE4FE2E2C767E61EFD"}}
	 * @apiSuccessExample {json} 支付宝支付
	 * {"status":1,"msg":"","data":{"torder_id":33536,"order_sn":"GHYM19052810344191","alipayinfo":{"url":"https:\/\/openapi.alipay.com\/gateway.do?alipay_sdk=alipay-sdk-php-20180705&app_id=2019052765396471&biz_content=%7B%22product_code%22%3A%22FAST_INSTANT_TRADE_PAY%22%2C%22out_trade_no%22%3A%22GHYM19052810344191P6524%22%2C%22total_amount%22%3A%220.01%22%2C%22subject%22%3A%22%5Cu56fd%5Cu5bb6%5Cu6d77%5Cu6d0b%5Cu535a%5Cu7269%5Cu9986%5Cu89c2%5Cu4f17%5Cu9884%5Cu7ea6%22%2C%22goods_type%22%3A0%2C%22timeout_express%22%3A%2230m%22%7D&charset=UTF-8&format=json&method=alipay.trade.page.pay¬ify_url=http%3A%2F%2Flocalhost%2Falinotify&sign=xnTXZJLB7sU31UrK2hNo%2FHqCtLWdNCSXmnB5Ibs7Vf0ppF3DtDch0nTzk53n8knHXxgNemqzJIppW8nN%2BBF%2BYxzVDyx%2FcC5XQhatEJIkhktTp3HaHieMnxyJ1vbxjEGrsx4EAhyECDst6urdbuDglc6AyNRp74DoRv0YM21PAkxJ0NRxF8LMZNclZrSs6ZU676zmkArZa3wc%2BgYCcXAoqnKoMBqbj2c08cBFftoSW3LwGqACNNsVG39XM566LP2vVE4xLo4W1n9TUUk2MRQjzXLgSI0QpzEFEW5q2v3HfxfexkLDiLbNX9On%2BWQI3ZzIxDd27KvR8%2FUNi9gxmpYdHA%3D%3D&sign_type=RSA2×tamp=2019-05-28+10%3A36%3A23&version=1.0"}}}
	 */
	public function pay()
	{
        $api_token = request('api_token');
        if (!Auth::user()) {
            return response_json(405, '', '登录已过期，请重新登录');
        }
        $uid = Auth::user()->uid;
        $user = Users::where('uid', $uid)->first();
        $money = request('money');
        if(!$money){
            return response_json(0, '', '请输入捐赠金额'); 
        }
        if($money<=0){
            return response_json(0, '', '捐赠金额不能为0'); 
        }
        $order_id = request('order_id');
        if(!$order_id){
            return response_json(0, '', '请选择需要捐赠的人'); 
        }
        $order = Orders::where('id',$order_id)->first();
        if(!$order){
            return response_json(0, '', '请刷新重试');
        }
        // $this->validate([
		// 	'torder_id' => 'required|integer',
		// 	'payment_id' => 'required|in:' . PAYMENT_ID_WXPAY . ',' . PAYMENT_ID_WXPAY_MINI . ',' . PAYMENT_ID_ALIPAY . ',' . PAYMENT_ID_YINLIAN
		// ], [], [
		// 	'torder_id' => '订单号',
		// 	'payment_id' => '支付方式'
        // ]);
        
        $donates = new Donates();
        $donates->title = $order->title;
        $donates->title = $order->title;
		$user = Auth::user();
        if($user){
            $uid = $user->uid;
        }else{
            $uid=0;
        }
		$openid = '';
        switch (request('p')) {
            case 'wx':
            case 'wxmini':
                // 取得用户openid
                $openid = UsersBind::where([
                    'uid' => $user->uid,
                    'b_from' => request('p')
                ])->value('openid');
                if (!$openid) {
                    // 根据用户查出unionid
                    $b_unionid = UsersBind::where(['uid' => $user->uid])->whereIn('b_from', [
                        'wx',
                        'wxmini'
                    ])->value('b_unionid');
                    // 根据unionid找出对应平台的openid
                    if ($b_unionid) {
                        $openid = UsersBind::where([
                            'b_unionid' => $b_unionid,
                            'b_from' => request('p')
                        ])->value('openid');
                    }
                    if (!$openid) {
                        throw new ApiErrorException('用户授权已失效，请刷新页面后重试');
                    }
                }
                break;
            default:
                break;
        }

		$order = TicketOrder::where([
			'order_status' => T_ORDER_UNPAY,
			'uid' => $uid
		])->select([
			'torder_id',
			'order_status',
			'order_sn',
			'out_trade_no',
			'order_amount',
			'payment_id',
            'created_at',
            'updated_at'
		])->find(request('torder_id'));
		if (is_null($order)) {
			throw new ApiErrorException('订单不存在或状态错误，请稍后重试');
		}

        if($order->created_at != $order->updated_at){
            //不是首次支付，则限制时间为五秒
            if(time() - strtotime($order->updated_at) < 5){
                throw new ApiErrorException("请勿频繁支付同一订单");
            }
        }

		$payment_id = request('payment_id');
		// 取得支付方式相关信息
		$payment = TicketPayment::findOrFail($payment_id);
		$payment_info = unserialize($payment->payment_info);

		if (($order->payment_id > 0 && $order->payment_id != $payment_id) || !$order->out_trade_no) {
		    if($order->out_trade_no){
                // 取得支付方式
                $payment1 = TicketPayment::select(['payment_info'])->find($order->payment_id);
                if (!is_null($payment1)) {
                    $payment_info1 = unserialize($payment1->payment_info);
                    $logObj = app('logext');
                    $logObj->init('order_qiehuan_pay');
                    // 到支付平台查询订单状态
                    switch ($order->payment_id) {
                        case PAYMENT_ID_WXPAY:
                            $wxapp = Factory::payment([
                                'app_id' => $payment_info1['wxAppId'],
                                'mch_id' => $payment_info1['wxMchId'],
                                'key' => $payment_info1['wxkey']
                            ]);
                            // 判断外部订单状态
                            $logObj->logbuffer('torder_id', $order->torder_id);
                            $logObj->logbuffer('out_trade_no', $order->out_trade_no);
                            $query_result = $wxapp->order->queryByOutTradeNumber($order->out_trade_no);

                            $logObj->logbuffer('wx_query_result', json_encode($query_result));
                            if (isset($query_result['return_code']) && $query_result['return_code'] == 'SUCCESS' && isset($query_result['trade_state']) && $query_result['trade_state'] == 'SUCCESS') {
                                // 支付成功，订单完成
                                TicketOrderDao::finish($order->torder_id, PAYMENT_ID_WXPAY, true, '通知超时，主动查询');
                                throw new ApiErrorException("支付成功，请不要支付同一个订单！");
                            }

                            break;
                        case PAYMENT_ID_ALIPAY:
                            $alipay = new \App\Utilities\Alipay\AopClient();
                            $alipay->appId = $payment_info1['appId'];
                            $alipay->signType = 'RSA2';
                            $alipay->rsaPrivateKey = file_get_contents($payment_info1['private_key_path']);
                            $alipay->alipayrsaPublicKey = file_get_contents($payment_info1['public_key_path']);
                            $alipay_query = new \App\Utilities\Alipay\Request\AlipayTradeQueryRequest();
                            $data['out_trade_no'] = $order->out_trade_no;

                            $logObj->logbuffer('torder_id', $order->torder_id);
                            $logObj->logbuffer('out_trade_no', $order->out_trade_no);

                            $alipay_query->setBizContent(json_encode($data));
                            $result = $alipay->execute($alipay_query);
                            $responseNode = str_replace(".", "_", $alipay_query->getApiMethodName()) . "_response";
                            $resultCode = $result->$responseNode->code;

                            $logObj->logbuffer('ali_query_result', json_encode($result));

                            if (!empty($resultCode) && $resultCode == 10000) {
                                $resultStatus = $result->$responseNode->trade_status;
                                if(in_array($resultStatus,["TRADE_SUCCESS","TRADE_FINISHED"])){
                                    // 支付成功，订单完成
                                    TicketOrderDao::finish($order->torder_id, PAYMENT_ID_ALIPAY, true, '通知超时，主动查询');
                                    throw new ApiErrorException("支付成功，请不要支付同一个订单！");
                                }
                            }
                            break;
                    }
                    $logObj->logend();

                }
            }
			// 支付方式改变，或不存在外部订单号，则重新生成外部订单号
			$order->out_trade_no = $order->order_sn . 'P' . rand(1000, 9999);
		} elseif ($order->payment_id > 0 && $order->out_trade_no) {
			// 根据支付方式查询订单
			switch ($payment_id) {
				case PAYMENT_ID_WXPAY:
				case PAYMENT_ID_WXPAY_MINI:
					// 微信及微信小程序
					// 实例化
					$wxapp = Factory::payment([
						'app_id' => $payment_info['wxAppId'],
						'mch_id' => $payment_info['wxMchId'],
						'key' => $payment_info['wxkey'],
						'notify_url' => $payment_info['notify_url']
					]);
					// 查询订单
					$query_result = $wxapp->order->queryByOutTradeNumber($order->out_trade_no);
					if (isset($query_result['err_code']) && $query_result['err_code'] == 'SYSTEMERROR') {
						throw new ApiErrorException('支付失败，请刷新后重试');
					}

					if (isset($query_result['return_code']) && $query_result['return_code'] == 'SUCCESS' && isset($query_result['trade_state']) && $query_result['trade_state'] == 'SUCCESS') {
						// 订单已支付，暂让用户等待支付结果
						throw new ApiErrorException('订单处理中，请稍后刷新页面');
					} else {
						// 订单未支付，则关闭订单
						$wxapp->order->close($order->out_trade_no);
						// 记录订单关闭日志
						$logObj = app('logext');
						$logObj->init('wxpay_prepare_query_close');
						$logObj->logbuffer('query_result', $query_result);
						$logObj->logbuffer('order_id', $order->torder_id);
						$logObj->logend();
						// 重置外部订单号
						$order->out_trade_no = $order->order_sn . 'P' . rand(1000, 9999);
					}
					break;
			}
		}

		// 保存支付方式
		$order->payment_id = $payment_id;
		$order->save();



		$returnData = [
			'torder_id' => $order->torder_id,
			'order_sn' => $order->order_sn
		];
		$subject = '深海纪元科技';
		// H5支付授权地址
        $wap_url = 'https://www.shenhaijiyuan.com/';
		// H5支付标题
		$wap_name = '滨海科技馆观众预约';
		switch ($payment_id) {
			case PAYMENT_ID_WXPAY:
			case PAYMENT_ID_WXPAY_MINI:

				$returnData['wxpayinfo'] = [];
				// 实例化
				$wxapp = Factory::payment([
					'app_id' => $payment_info['wxAppId'],
					'mch_id' => $payment_info['wxMchId'],
					'key' => $payment_info['wxkey'],
					'notify_url' => $payment_info['notify_url']
				]);
				// 微信支付参数
				$wxpay_params = [
					'body' => $subject,
					'out_trade_no' => $order->out_trade_no,
					'total_fee' => intval($order->order_amount * 100),
				];

				switch (request('p')) {
					case 'w':
						// 扫码支付id，区分平台
						$scheme_id = 'pw_' . $order->torder_id;
						// 网页微信扫码支付
						return response_json(1, [
							'qrcode' => $wxapp->scheme($scheme_id)
						]);
						break;
					case 't':
						// 触屏
						$wxpay_params['trade_type'] = 'MWEB';
						$wxpay_params['scene_info'] = '{"h5_info":{"type":"Wap","wap_url":"' . $wap_url . '","wap_name": "' . $wap_name . '"}}';
						$wxpay_params['spbill_create_ip'] = client_real_ip();
						break;
					case 'wx':
					case 'wxmini':
						if (!$openid) {
							throw new ApiErrorException('缺少授权信息，请刷新页面后重试');
						}
						// 公众号及小程序
						$wxpay_params['trade_type'] = 'JSAPI';
						$wxpay_params['openid'] = $openid;
						break;
					default:
						throw new ApiErrorException('error plat');
						break;
				}

				// 统一下单
				$result = $wxapp->order->unify($wxpay_params);

				// 记录日志
				if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
					switch (request('p')) {
						case 't':
							// H5支付
							$returnData['wxpayinfo'] = ['mweb_url' => $result['mweb_url']];
							break;
						case 'wx':
						case 'wxmini':
							// 公众号支付，小程序支付
							$wxpayinfo = [
								'appId' => $payment_info['wxAppId'],
								'timeStamp' => strval(time()),
								'nonceStr' => uniqid(),
								'package' => 'prepay_id=' . $result['prepay_id'],
								'signType' => 'MD5'
							];
							// 生成签名
							$wxpayinfo['paySign'] = generate_sign($wxpayinfo, $payment_info['wxkey'], 'md5');
							$returnData['wxpayinfo'] = $wxpayinfo;
							break;
						default:
							throw new ApiErrorException('error plat');
							break;
					}

				} else {
					$logObj = app('logext');
					$logObj->init('wxpay_prepare_error');
					$logObj->logbuffer('result', $result);
					$logObj->logbuffer('order_id', $order->torder_id);
					$logObj->logend();

					if (isset($result['err_code']) && $result['err_code'] == 'SYSTEMERROR') {
						throw new ApiErrorException('支付失败，请刷新后重试');
					}

					// 查询订单
					$query_result = $wxapp->order->queryByOutTradeNumber($order->out_trade_no);
					if (isset($query_result['return_code']) && $query_result['return_code'] == 'SUCCESS' && isset($query_result['trade_state']) && $query_result['trade_state'] == 'SUCCESS') {
						// 订单已支付
						throw new ApiErrorException('订单处理中，请稍后刷新页面');
					} else {
						// 订单未支付，则关闭订单
						$wxapp->order->close($order->out_trade_no);

						$logObj = app('logext');
						$logObj->init('wxpay_prepare_query_close');
						$logObj->logbuffer('prepare_result', $result);
						$logObj->logbuffer('query_result', $query_result);
						$logObj->logbuffer('order_id', $order->torder_id);
						$logObj->logend();

						// 重置外部订单号
						$order->out_trade_no = '';
						$order->save();

						throw new ApiErrorException('支付失败，请刷新后重试');
					}
				}
				break;
			case PAYMENT_ID_ALIPAY:
				$alipay = new AopClient();
				$alipay->appId = $payment_info['appId'];
				$alipay->signType = 'RSA2';
				$alipay->rsaPrivateKey = file_get_contents($payment_info['private_key_path']);
				$alipay->alipayrsaPublicKey = file_get_contents($payment_info['public_key_path']);

				if (request('p') == 'w') {
					$alipay_request = new AlipayTradePagePayRequest();
				} elseif (request('p') == 't') {
					$alipay_request = new AlipayTradeWapPayRequest();
				} else {
					throw new ApiErrorException('支付方式选择错误，请返回重试');
				}

				// 支付返回地址
                //https://www.bhstm.com/w/home/ticket/complete?torder_id=8
                $alipay_request->setReturnUrl(env('WEB_URL','https://www.bhstm.com').'/w/home/ticket/complete?torder_id='.$order->torder_id);
				// 支付异步通知地址
				$alipay_request->setNotifyUrl($payment_info['notify_url']);
				// 支付参数
				$alipay_request->setBizContent(json_encode([
					'product_code' => 'FAST_INSTANT_TRADE_PAY',
					// 外部订单号
//					'out_trade_no' => 'pw_' . $order->out_trade_no,
					'out_trade_no' =>  $order->out_trade_no,
					// 支付金额
					'total_amount' => $order->order_amount,
					// 标题
					'subject' => $subject,
					// 虚拟商品类型，不支持花呗
					'goods_type' => 0,
					// 超时时间，30分钟
					'timeout_express' => '30m'
				]));


				$alipay_url = $alipay->pageExecute($alipay_request, 'GET');

				$returnData['alipayinfo'] = ['url' => $alipay_url];
				break;
		}

		return response_json(1, $returnData);
	}
}
